﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using Security;
using GeoRef;

namespace TripLOA.GUI
{
    public partial class PassengerTripDetail : TripLOA.GUI.internationalization.LOABasePage
    {
    #region Variables

        private int numPass = 0;
        private Groupware.Trip trip = null;

        private string username = null;
        private List<Security.Profile> passengers = new List<Security.Profile>();
        private List<Groupware.Trip> tripDetail = new List<Groupware.Trip>();
        private List<Groupware.Stage> stages = null;
        private string tripId;
        private Security.TripLoaUser us = null;

        private int th_is_FreeSeat;
        private int page_number = 0;//the page number of the stages GridView
    
    #endregion Variables

    #region Event handlers

        protected void Page_Load(object sender, EventArgs e)
        {
            uint? tripIdentificator = null;
            
            map2_id.GoogleApiKey = System.Configuration.ConfigurationManager.AppSettings["googlekey"];
            map1_id.GoogleApiKey = System.Configuration.ConfigurationManager.AppSettings["googlekey"];
            tripId = (string)Request.QueryString["Trip"];
            try
            {
                tripIdentificator = Convert.ToUInt32(tripId);
            }
            catch (FormatException) { }

            // On every request Groupware.Trip object needs to be recreated
            if (tripIdentificator.HasValue)
            {
                trip = Groupware.TripManager.GetTripById(Convert.ToInt32(tripIdentificator.Value));
            }

            if (trip == null)
            {
                viewPassengersList.Visible = false;
                viewStages.Visible = false;
                viewTripDetail.Visible = false;
                presencePanel.Visible = false;
                contentPanel.Visible = false;
            }
            else
            {
                
                
                                              
                try
                {
                    //Get current logged-in user
                    us = TripLoaUserManager.Instance.getUser(User.Identity.Name);
                }
                catch (Exception)
                {
                    //User is guest
                    us = null;
                    //viewPresenceRequest.Visible = false;
                }
                
                
               
                GeoRef.GeoTrip gt = trip.GetGeoTrip();
                
                if ((us == null || us.UserID == trip.UserId) || (us!=null &&( trip.IsRequestingReservation(us)|| trip.IsReserved(us)) ))
                {
                    presencePanel.Visible = false;
                    map1_id.Visible = true;
                    map2_id.Visible = false;
                    //Map control
                    map1_id.DrawTrip(gt);
                }
                else
                {
                    map1_id.Visible = false;
                    map2_id.Visible = true;
                    //Map control
                    map2_id.DrawTrip(gt);
                }

                //get the nickname of the trip's author
                if (us != null)
                    username = us.GetProfile((int)trip.UserId).Username;

                tripDetail.Add(trip);

                if (!IsPostBack)
                {   
                   
                    startPoint.Text = trip.Departure;
                    endPoint.Text = trip.Arrival;
                    latlongStart.Value = gt.Start.ToString();
                    latlongEnd.Value = gt.End.ToString();
                    noSeats.Text = "1";
                    startPointTolerance.Text = "2";
                    endPointTolerance.Text = "2";
                    th_is_FreeSeat = 1;
                    
                    //set property for the frequency control
                    if (trip.IsFrequent != null && (bool)trip.IsFrequent)
                    {
                        ptc.Editable = false;
                        ptc.DeparturesTime = trip.GetFrequencyDetails();

                        if (trip.EstimatedTime != null)
                        {
                            int estimated=(int)trip.EstimatedTime;
                            ptc.TripDuration = new TimeSpan(0, estimated, 0);
                        }
                            
                    }
                                                                              
                }

                //Get passengers list that join in a trips
                if (us != null)
                {
                    passengers = trip.GetPassengersProfiles(us);
                    numPass = passengers.Count;
                }
               

                //get the stage's list
                stages = trip.Stages();

                //trip.IsReserved(us);

                                               
            }
        }

        //view a default string for an empty passenger list
        protected void noPassenger_OnInit(object sender, EventArgs e)
        {

            Label l = (Label)sender;
            if (numPass == 0)
                l.Visible = true;
            else
                l.Visible = false;


        }

        //Event for handle the stages paging
        protected void detailViewStages_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            tripDetailsView.DataSource = tripDetailsView.DataSource as DataTable;
            page_number = e.NewPageIndex;
            detailViewStages.PageIndex = e.NewPageIndex;

            detailViewStages.DataBind();

        }

        //Event to load data in the trip detail DetailView
        protected void tripDetail_PreRender(object sender, EventArgs e)
        {
            tripDetailsView.DataSource = tripDetail;
            tripDetailsView.DataBind();

            if (trip != null)
            {
                HyperLink authorLink = (HyperLink)tripDetailsView.Rows[0].FindControl("AuthLink");
                if (us != null)
                {
                    authorLink.Text = username;
                    loadUrl(authorLink);
                }
                else tripDetailsView.Rows[0].Visible = false;

                Label v = (Label)tripDetailsView.Rows[3].FindControl("vehicle");
                String internationalvehicle = (String)HttpContext.GetLocalResourceObject("~/PassengerTripDetail.aspx", stages[0].Vehicle.Model);
                if (internationalvehicle != null) v.Text = internationalvehicle;
                else v.Text = stages[0].Vehicle.Model;


                switch (stages[0].Vehicle.VehicleClass)
                {
                    case Storage.EntityModels.VehicleTypes.Car:
                        break;
                    case Storage.EntityModels.VehicleTypes.Train:
                        viewTAS();
                        th_is_FreeSeat = 0;
                        break;
                    case Storage.EntityModels.VehicleTypes.Airplane:
                        viewTAS();
                        th_is_FreeSeat = 0;
                        break;
                    case Storage.EntityModels.VehicleTypes.Bike:
                        //free seats
                        tripDetailsView.Rows[5].Visible = false;
                        th_is_FreeSeat = 0;
                        viewBM();
                        break;
                    case Storage.EntityModels.VehicleTypes.Motorcycle:
                        viewBM();
                        break;
                    case Storage.EntityModels.VehicleTypes.Ship:
                        th_is_FreeSeat = 0;
                        viewTAS();
                        break;

                }

                validateSeatField();

                DateTime dep_date = Convert.ToDateTime(trip.DepartureDate);
                Label departureLabel = (Label)tripDetailsView.FindControl("departureDate");

                if (trip.IsFrequent == null || !(bool)trip.IsFrequent)
                {
                    hideFrequencyField();
                    departureLabel.Text = dep_date.ToString();

                }
                else
                {
                    //estimated time
                    tripDetailsView.Rows[8].Visible = false;
                    departureLabel.Text = dep_date.ToString("dd/mm/yyyy");

                }
            }


        }
        //Event to load data in the passengers ListView
        protected void passengers_PreRender(object sender, EventArgs e)
        {
            passengerList.DataSource = passengers;
            passengerList.DataBind();

        }

        //Event to load data in the stages GridView
        protected void stages_PreRender(object sender, EventArgs e)
        {
            detailViewStages.DataSource = stages;
            detailViewStages.DataBind();


            //format the string for the place object

            if (trip != null)
                setOriginDestination(page_number, detailViewStages.PageSize);

        }

        //update the passenger position in the map
        protected void UpdateMap_Click(object sender, EventArgs e)
        {
            double fromTol;
            double toTol;

            if (us != null)
            {
                bool isCorrect = validateData(startPoint.Text, endPoint.Text, noSeats.Text, startPointTolerance.Text, endPointTolerance.Text);
                if (isCorrect)
                {

                    try
                    {
                        fromTol = double.Parse(startPointTolerance.Text);
                        toTol = double.Parse(endPointTolerance.Text);
                    }
                    catch (FormatException)
                    {
                        return;
                    }
                    GeoLoc from = getLoc(latlongStart, startPoint.Text);
                    GeoLoc to = getLoc(latlongEnd, endPoint.Text);
                    if (from != null && to != null)
                    {
                        map2_id.SetPassenger(us.UserID, from, fromTol, to, toTol);
                        map2_id.InvokeJSCommand("GEvent.addListener(this._map._passengerDep, 'dragend2', this._stuff.passengerHandler)");
                        map2_id.InvokeJSCommand("GEvent.addListener(this._map._passengerArr, 'dragend2', this._stuff.passengerHandler)");
                    }
                }
            }
        }

        //the event that handle the join trip
        protected void buttonJoin_Click(object sender, EventArgs e)
        {
            if (us == null)
                Response.Redirect("registration.aspx");
            else
            {
                float fromTol;
                float toTol;
                bool isCorrect = validateData(startPoint.Text, endPoint.Text, noSeats.Text, startPointTolerance.Text, endPointTolerance.Text);
                if (isCorrect)
                {
                    errorsMessage.Visible = false;
                    try
                    {
                        fromTol = float.Parse(startPointTolerance.Text);

                        toTol = float.Parse(endPointTolerance.Text);
                    }
                    catch (FormatException)
                    {
                        return;
                    }

                    int seats = Convert.ToInt32(noSeats.Text);
                    GeoLoc fromLoc;
                    GeoLoc toLoc;
                    //get GeoLoc from the map
                    fromLoc = map2_id.PassengerDeparture;
                    toLoc = map2_id.PassengerArrive;

                    string errors = null;

                    if (fromLoc == null || toLoc == null)
                    {
                        //get passenger position from the hidden field with the correct position
                        fromLoc = getLoc(latlongStart, startPoint.Text);
                        toLoc = getLoc(latlongEnd, endPoint.Text);
                        //the place not exist
                        if (fromLoc == null || toLoc == null)
                            errors = Resources.TripLoaResource.NotCorrectParPTD;

                    }

                    //control on the number of seat
                    if (th_is_FreeSeat != 1 ||(seats > 0 && seats <= trip.FreeSeats && errors == null))
                    {
                        try
                        {

                            trip.RequestToJoin(us, Convert.ToByte(seats), fromLoc, toLoc, fromTol, toTol, tripComment.Text);
                            Response.Redirect("secure/Home.aspx");

                        }

                        catch (Groupware.OperationNotAllowedException)
                        {
                            errors = Resources.TripLoaResource.ONAExeptionPTD;
                        }
                        catch (Groupware.Trip.NotPublishedException)
                        {
                            errors = Resources.TripLoaResource.NPExeptionPTD;
                        }
                        catch (Groupware.Trip.StillAccomplishedException)
                        {
                            errors = Resources.TripLoaResource.SAExeptionPTD;
                        }
                        catch (Groupware.Trip.ReservationTimeExpiredException)
                        {
                            errors = Resources.TripLoaResource.RTEExeptionPTD;
                        }
                        catch (Groupware.Trip.ReservationRequestStillSubmitted)
                        {
                            errors = Resources.TripLoaResource.RRSSExeptionPTD;
                        }
                        catch (Groupware.Trip.ReservationStillConfirmedException)
                        {
                            errors = Resources.TripLoaResource.RSCExeptionPTD;
                        }

                        catch (Groupware.ParametersException ex)
                        {

                            //start too far
                            if ((Exception)ex.Data["start"] is Groupware.ReservationRequest.InvalidStartPointException)
                                errors = Resources.TripLoaResource.StartTooFarPTD;

                            //end too far
                            if ((Exception)ex.Data["end"] is Groupware.ReservationRequest.InvalidEndPointException)
                            {

                                if (errors != null)
                                    errors = Resources.TripLoaResource.EndStartTooFarPTD;
                                else
                                    errors = Resources.TripLoaResource.EndTooFarPTD;

                            }

                        }

                    }
                    else errors = Resources.TripLoaResource.NotCorrectParPTD;
                    //view an error message
                    if (errors != null)
                    {
                        errorsMessage.Visible = true;
                        errorsMessage.Text = errors;
                    }

                }


            }

        }


        protected void tripComment_TextChanged(object sender, EventArgs e)
        {

        }
    
    #endregion

    #region Private methods


        //pass the number of free seats to the javascript function for the validation
        private void validateSeatField()
        {
            noSeats.Attributes.Add("onchange", "return validateSeat(" + Convert.ToInt32(trip.FreeSeats) + "," + Convert.ToInt32(th_is_FreeSeat) + ")");
            
        }

        //set the correct url for the author's link
        protected void loadUrl(HyperLink authorLink)
        {

            if (authorLink != null && us != null)
            {

                if (us.GetProfile().Username == username)
                    authorLink.NavigateUrl = "../secure/userProfile.aspx";
                else
                    authorLink.NavigateUrl = "../secure/userProfile.aspx?Nick=" + authorLink.Text;

            }
            else if (us == null)
                Response.Redirect("registration.aspx");

        }

        

        //set the correct format for the origin and destination label in the stages GridView
        private void setOriginDestination(int npage, int page_size)
        {
            Label origin;
            Label destination;
            int n = detailViewStages.Rows.Count;

            for (int i = 0; i < n; i++)
            {
                origin = (Label)detailViewStages.Rows[i].FindControl("origin");
                destination = (Label)detailViewStages.Rows[i].FindControl("destination");
                //real stage index
                int j = i + page_size*npage;
                origin.Text = getPlace(stages[j].Origin);
                destination.Text = getPlace(stages[j].Destination);

            }

        }

        //Convert the place info in a string with the correct format
        private string getPlace(Groupware.Place place)
        {
            List<string> place_info = new List<string>();
            place_info.Add((string)place.Address); 
            place_info.Add((string)place.City);
            place_info.Add((string)place.Province);
            place_info.Add((string)place.State);
            string p = "";

            foreach (string info in place_info)
            {
                if (info != "" && p!="")
                    p = p + "," + info;
                else if (info != "" && p == "")
                    p = p + info;
            }

            return p;

        }
        //hide some field when there is a frequancy trip
        private void hideFrequencyField()
        {   
            //Time From
            tripDetailsView.Rows[11].Visible = false;
            //Time To
            tripDetailsView.Rows[12].Visible = false;
            //detail frequency button
            tripDetailsView.Rows[13].Visible = false;
            
            
        }
        //hide the Bike and Moto field
        private void viewBM()
        {
            tripDetailsView.Rows[14].Visible = false;
            tripDetailsView.Rows[15].Visible = false;
            
        }
        //hide the Train, Airplane and Ship field
        private void viewTAS()
        {
            //free seats
            tripDetailsView.Rows[5].Visible = false;
            //deviation radius
            tripDetailsView.Rows[9].Visible = false;
            //accept smoker
            tripDetailsView.Rows[14].Visible = false;
            //license
            tripDetailsView.Rows[15].Visible = false;


        }
        //control that the empty field for textbox
        private bool validateData(string from, string to, string seats, string startTol, string endTol)
        {

            if (from != "" && to != "" && seats != "" && startTol != "" && endTol != "")
                return true;
            return false;

        }
        
        

        //convert a string into GeoLoc
        private GeoLoc getLoc(HiddenField locH, string locText)
        {
            GeoLoc loc = null;
            GeoQuery q = new GeoQuery();

            try
            {
                if (locH != null && locH.Value != "")
                {
                    loc = new GeoLoc(locH.Value, locText, "");
                }
                else if (startPoint.Text != "")
                {

                    loc = q.geoCoding(locText).First();
                }

            }
            catch (GeoRef.Exceptions.GeoCodingException)
            {
               return null;
            }
            return loc;
        }


    #endregion

    }
}
    